import datetime
import logging
import execjs
from utils.spider_utils import *


class Spiders(object):

    years = [str(i + 2013) for i in range(7)]
    month = [str(i if i > 9 else '0' + str(i)) for i in range(1, 13)]
    now_y, now_m, now_d = datetime.datetime.now().strftime('%Y-%m-%d').split('-')
    ctx = execjs.get().compile(open('source/decrypt.js', encoding='utf-8').read())

    # 爬取某城市 月平均
    @staticmethod
    def get_month_average_info_by_city(self, city):
        result = []
        date_time = ''  # 201805
        html_info = get_response(month_params(city, date_time, self.ctx))
        if html_info is not None:
            item = decode_info(html_info, self.ctx)
            for i in item['result']['data']['items']:
                result.append(en_month_dict_to_list(city, i))
                logging.info('获取' + city + str(i['time_point']) + '的月平均数据')
        else:
            logging.info(city + '的月平均数据异常')
        return result

    # 爬取某城市一年的日数据
    @staticmethod
    def get_year_info_by_city(self, year, city):
        result = []
        for m in self.month:
            # 当 时间 是当前时间时 跳出循环
            if self.now_y == year and self.now_m == m:
                break
            date_time = year + m
            html_info = get_response(day_params(city, date_time, self.ctx))
            print('爬取' + date_time + city)
            if html_info is not None:
                item = decode_info(html_info, self.ctx)
                for i in item['result']['data']['items']:
                    result.append(i)
        return result

    # 得到一个城市最近一天的数据
    @staticmethod
    def get_least_info_by_city(self, city):
        result = []
        date_time = self.now_y + self.now_m  # 201805
        html_info = get_response(day_params(city, date_time, self.ctx))
        if html_info is not None:
            item = decode_info(html_info, self.ctx)
            last_num = len(item['result']['data']['items'])
            if last_num is 0:
                logging.info(city + '无最近数据或未更新')
            else:
                logging.info('获取' + city + str(item['result']['data']['items'][-1]['time_point']) + '数据')
                result = [en_day_sdict_to_list(city, item['result']['data']['items'][-1])]
        return result

    # 得到一个城市所有的历史数据
    @staticmethod
    def get_all_info_by_city(self, city):
        result = []
        for y in self.years:
            for m in self.month:
                # 当 时间 是当前时间时 跳出循环
                if self.now_y == y and self.now_m == m:
                    break
                date_time = y + m
                html_info = get_response(day_params(city, date_time, self.ctx))
                print('爬取' + date_time + city)
                if html_info is not None:
                    item = decode_info(html_info, self.ctx)
                    for i in item['result']['data']['items']:
                        result.append(en_day_sdict_to_list(city, i))
        return result
